package orchestration.android;

import orchestration.persistence.OrchestratorAuthority.AndroidProcess;
import orchestration.persistence.OrchestratorAuthority.AndroidProcessExecution;
import orchestration.persistence.sqlite.OrchestratorDatabaseHelper;
import android.app.ListActivity;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
/**
 * List details for the given process, including its Executions.
 * This activity also allows to create new Executions for the given proces,
 * or to choose an Execution from the created ones
 * @author <a href="mailto:car.ferrarini@gmail.com">Carlo Ferrarini</a>
 *
 */
public class ProcessDetailsActivity extends ListActivity{

	// Menu item ids
	public static final int MENU_ITEM_DELETE = Menu.FIRST;
	public static final int MENU_ITEM_INSERT = Menu.FIRST + 1;
	
	private Long mProcId;
	private String mProcName;
	private String mProcPath;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Uri uri= getIntent().getData();
		Cursor procCursor= managedQuery(uri, 
				OrchestratorDatabaseHelper.PROCESS_FIELDS, null, null, null);
		procCursor.moveToFirst();
		if(procCursor.isAfterLast()){
			Toast.makeText(this, "Process not Found!", Toast.LENGTH_SHORT).show();
			finish();
			return;
		}
		mProcId=procCursor.getLong(procCursor.getColumnIndex(AndroidProcess._ID));
		mProcName= procCursor.getString(procCursor.getColumnIndex(AndroidProcess.NAME));
		mProcPath= procCursor.getString(procCursor.getColumnIndex(AndroidProcess.PATH));
		
		
		/**
		 * TODO manage menus & possible operations
		 */
		setContentView(R.layout.process_details);
		TextView name= (TextView)findViewById(R.id.text_process_name);
		TextView path= (TextView)findViewById(R.id.text_process_path);
		Button button= (Button) findViewById(R.id.new_execution_button);
		final EditText newExecutionName= (EditText) findViewById(R.id.new_execution_name);
		button.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				newExecution(newExecutionName.getText().toString());
			}
		});
		name.setText(mProcName);
		path.setText("path: "+mProcPath);
	
		// Inform the list we provide context menus for items
		getListView().setOnCreateContextMenuListener(this);
	}
	
	
	
	@Override
	protected void onResume() {
		super.onResume();
		fillList();
	}

	private void fillList() {
		String selection=AndroidProcessExecution.NAME+"!='' AND "+ AndroidProcessExecution.PROCESS_REF+"=?";
		String[] selectionArgs= new String[1];
		selectionArgs[0]=""+mProcId;
		Cursor instCursor= managedQuery(AndroidProcessExecution.CONTENT_URI,
				OrchestratorDatabaseHelper.EXECUTION_FIELDS, selection, selectionArgs, AndroidProcessExecution.DEFAULT_SORT_ORDER);
		SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.execution_list_item, instCursor,
				new String[] { AndroidProcessExecution.NAME, AndroidProcessExecution.EXECUTION_STATUS }, new int[] { R.id.text_execution_name, R.id.text_execution_status });
		setListAdapter(adapter);
	}
	
    @Override
    public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo) {
    	AdapterView.AdapterContextMenuInfo info;
        try {
             info = (AdapterView.AdapterContextMenuInfo) menuInfo;
        } catch (ClassCastException e) {
            return;
        }

        Cursor cursor = (Cursor) getListAdapter().getItem(info.position);
        if (cursor == null) {
            // For some reason the requested item isn't available, do nothing
            return;
        }

        // Setup the menu header
        menu.setHeaderTitle(cursor.getString(1));

        // Add a menu item to delete the process
        menu.add(Menu.NONE, MENU_ITEM_DELETE, Menu.NONE, R.string.menu_delete_process_execution);
    }
        
    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterView.AdapterContextMenuInfo info;
        try {
             info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        } catch (ClassCastException e) {
            return false;
        }

        switch (item.getItemId()) {
            case MENU_ITEM_DELETE: {
                // Delete the process that the context menu is for
                Uri executionUri = ContentUris.withAppendedId(AndroidProcessExecution.CONTENT_URI, info.id);
                getContentResolver().delete(executionUri, null, null);
                return true;
            }
        }
        return false;
    }
    
    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        Uri uri = ContentUris.withAppendedId(AndroidProcessExecution.CONTENT_URI, id);
        
        String action = getIntent().getAction();
        if ((Intent.ACTION_PICK.equals(action) || Intent.ACTION_GET_CONTENT.equals(action)) && AndroidProcessExecution.CONTENT_URI.equals(getIntent().getData())) {
            // The caller is waiting for us to return an execution selected by
            // the user.
            setResult(RESULT_OK, new Intent().setData(uri));
        } else{
        	//standard behaviour: start the service that manages BPs and launch an activity that works with it
        	startService(new Intent().setAction(Intent.ACTION_RUN).setData(getIntent().getData()));
            startActivityForResult(new Intent().setAction(Intent.ACTION_RUN).setData(uri),0);
        }
    }


	/**
	 * if execution name is valid, creates a new execution and updates the list, else notify with a popup 
	 * @param executionName
	 */
	private void newExecution(String executionName) {
		ContentValues cv= new ContentValues();
		if(executionName==null || executionName==""){
			Toast.makeText(ProcessDetailsActivity.this, "name cannot be null", Toast.LENGTH_SHORT).show();
		}else{
			cv.put(AndroidProcessExecution.NAME, executionName);
			cv.put(AndroidProcessExecution.PROCESS_REF, mProcId);
			getContentResolver().insert(AndroidProcessExecution.CONTENT_URI, cv);
			fillList();
		}
	}
}